package com.jilin.library.service;

import com.jilin.library.dto.LoginRequest;
import com.jilin.library.dto.LoginResponse;
import com.jilin.library.entity.Admin;
import com.jilin.library.mapper.AdminMapper;
import com.jilin.library.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    public LoginResponse login(LoginRequest request) {
        Admin admin = adminMapper.findByUsername(request.getUsername());
        logger.debug("Login attempt for username: {}", request.getUsername());
        logger.debug("Found admin: {}", admin);
        
        if (admin == null) {
            logger.debug("Admin not found");
            throw new RuntimeException("用户名或密码错误");
        }
        
        logger.debug("Stored password: {}", admin.getPassword());
        logger.debug("Input password: {}", request.getPassword());
        boolean matches = passwordEncoder.matches(request.getPassword(), admin.getPassword());
        logger.debug("Password matches: {}", matches);
        
        if (!matches) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        LoginResponse response = new LoginResponse();
        response.setToken(jwtUtil.generateToken(admin.getUsername()));
        response.setName(admin.getName());
        return response;
    }
} 